<template>
  <div class="content">
    <video class="video" src="" ref="video"></video>
    <canvas class="canvas" ref="canvas"></canvas>
  </div>
</template>

<script>
import jsQR from "jsqr";

export default {
  data() {
    return {
      timer: null,
      result: "",
      imgurl: "",
      isAnimation: true,
      audio: null,
      video: null,
      cvsele: null,
      canvas: null,
    };
  },
  mounted() {
    this.audio = new Audio("./tone.mp3");
    // this.video = document.createElement("video");
    this.video = this.$refs.video;
    this.cvsele = this.$refs.canvas;
    this.canvas = this.cvsele.getContext("2d");
    // this.media();
  },
  methods: {
    draw(begin, end) {
      this.canvas.beginPath();
      this.canvas.moveTo(begin.x, begin.y);
      this.canvas.lineTo(end.x, end.y);
      this.canvas.lineWidth = 3;
      this.canvas.strokeStyle = "red";
      this.canvas.stroke();
    },
    cance() {
      this.isAnimation = false;
      cancelAnimationFrame(this.timer);
      setTimeout(() => {
        this.cvsele.style.display = "none";
      }, 1000);
    },
    sweep() {
      if (this.video.readyState === this.video.HAVE_ENOUGH_DATA) {
        const { videoWidth, videoHeight } = this.video;
        this.cvsele.width = videoWidth;
        this.cvsele.height = videoHeight;
        this.canvas.drawImage(this.video, 0, 0, videoWidth, videoHeight);
        try {
          const img = this.canvas.getImageData(0, 0, videoWidth, videoHeight);
          this.imgurl = img;
          const obj = jsQR(img.data, img.width, img.height, {
            inversionAttempts: "dontInvert",
          });
          if (obj) {
            const loc = obj.location;
            this.draw(loc.topLeftCorner, loc.topRightCorner);
            this.draw(loc.topRightCorner, loc.bottomRightCorner);
            this.draw(loc.bottomRightCorner, loc.bottomLeftCorner);
            this.draw(loc.bottomLeftCorner, loc.topLeftCorner);
            if (this.result != obj.data) {
              this.audio.play();
              this.result = obj.data;
              this.cance();
              console.info("识别结果：", obj.data);
            }
          } else {
            console.error("识别失败，请检查二维码是否正确！");
          }
        } catch (err) {
          console.error("识别失败，请检查二维码是否正确！", err);
        }
      }
      if (this.isAnimation) {
        this.timer = requestAnimationFrame(() => {
          this.sweep();
        });
      }
    },

    media() {
      this.isAnimation = true;
      this.cvsele.style.display = "block";
      navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
      if (navigator.mediaDevices) {
        navigator.mediaDevices.getUserMedia({
          video: { facingMode: "environment" },
        }).then((stream) => {
          this.video.srcObject = stream;
          this.video.setAttribute("playsinline", true);
          this.video.setAttribute("webkit-playsinline", true);
          this.video.addEventListener("loadedmetadata", () => {
            this.video.play();
            this.sweep();
          });
        }).catch((error) => {
          this.cance();
          alert('对不起：未识别到扫描设备!');
          console.log(error.code + "：" + error.name + "，" + error.message);
        });
      } else if (navigator.getUserMedia) {
        navigator.getUserMedia({
          video: { facingMode: "environment" },
        }, (stream) => {
          this.video.srcObject = stream;
          this.video.setAttribute("playsinline", true);
          this.video.setAttribute("webkit-playsinline", true);
          this.video.addEventListener("loadedmetadata", () => {
            this.video.play();
            this.sweep();
          });
        }, (error) => {
          this.cance();
          alert('对不起：未识别到扫描设备!');
          console.log(error.code + "：" + error.name + "，" + error.message);
        }
        );
      } else {
        if (navigator.userAgent.toLowerCase().match(/chrome/) && location.origin.indexOf("https://") < 0) {
          console.log("获取浏览器录音功能，因安全性问题，需要在localhost 或 127.0.0.1 或 https 下才能获取权限！");
        } else {
          this.cance();
          alert("对不起：未识别到扫描设备!");
        }
      }
    },

  },
}
</script>

<style lang="less" scoped>
.content {
  width: 100vw;
  height: 100vh;
  // background-color: #000;
  background-color: aquamarine;
  overflow: hidden;
  position: fixed;
  top: 0;
  left: 0;
}

.video {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  // background: red;
}

.canvas {
  display: none;
  box-sizing: border-box;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
}
</style>